package com.example.yilanchatserver.business.freechat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.yilanchatserver.business.freechat.FuJiaSubscriber;
import com.example.yilanchatserver.business.freechat.UtopiaSubscriber;
import com.example.yilanchatserver.business.freechat.ZhiPuPromptSubscriber;
import com.example.yilanchatserver.business.freechat.service.FuJiaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author : lank
 * @since : 2024-10-18
 * impl
 */
@Slf4j
@Service
public class FuJiaServiceImpl implements FuJiaService {
    private WebClient webClient;

    private  String appkey = "cda851f488784e16a98819ee868a48ce";
    private  String appsercet = "6ccf25c6eefd48e6ab41812942f59fa7";

    private String appUrl = "https://api-botx.dingtax.cn/bot/api/v1/open/llm/chat/id4ZgWuT9fdWPcLbgJVqxVhP";


    /**
     * dev采用代理访问
     */
    @PostConstruct
    public void init() {
        initProd();
    }


    public void initProd() {
        log.info("initProd");
        this.webClient = WebClient.builder()
                .defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .build();
    }


    @Override
    public Flux<String> send(String question) {
        log.info("收到问题=============:" + question);
        return Flux.create(emitter -> {

            FuJiaSubscriber subscriber = new FuJiaSubscriber(emitter);
            JSONObject talkerParams = new JSONObject();
            talkerParams.put("question", question);
            talkerParams.put("needSimplifyMessage", true);

            log.info("开始请求接口----------->");
            long time = System.currentTimeMillis() / 1000;
            String sign = DigestUtils.md5Hex(appsercet + "appkey" + appkey + "t" + time);
            Flux<String> fuJisResponse = webClient.post()
                    .uri(appUrl + "?appkey=" + appkey + "&sign=" + sign + "&t=" + time)
                    .accept(MediaType.TEXT_EVENT_STREAM)
                    .bodyValue(talkerParams.toJSONString())
                    .retrieve()
                    .bodyToFlux(String.class)
                    .onErrorResume(WebClientResponseException.class, ex -> {
                        HttpStatus status = ex.getStatusCode();
                        String res = ex.getResponseBodyAsString();
                        log.error("OpenAI API error: {} {}", status, res);
                        return Mono.error(new RuntimeException(res));
                    });
            log.info("结束请求接口----------->");
            fuJisResponse.publishOn(Schedulers.parallel()).subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }
}
